class Hotkey {
    hotkeys = {}
    hotkeysConfig = {}
    handleKeyDownEvent
    constructor() {
        this.handleKeyDownEvent = e => this.handleKeyDown(e)
        document.addEventListener('keydown', this.handleKeyDownEvent, true);
    }
    destroy() {
        this.hotkeys = {};
        document.removeEventListener('keydown', this.handleKeyDownEvent, true);
    }
    addHotkey(combo: string, callback, { macOnly = false, windowsOnly = false } = {}, stop = false) {
        if ((macOnly && !navigator.platform.startsWith('Mac')) || (windowsOnly && navigator.platform.startsWith('Mac'))) {
            return;
        }
        const _combo = combo.toLocaleLowerCase();
        if (!this.hotkeys[_combo]) {
            this.hotkeys[_combo] = [];
        }
        if (!this.hotkeysConfig[_combo]) {
            this.hotkeysConfig[_combo] = stop;
        }
        this.hotkeys[_combo].push(callback);
    }
    handleKeyDown(event) {
        // 检查当前活动元素是否为input或textarea
        const activeElement = document.activeElement;
        if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA')) {
            return; // 如果是，不执行快捷键
        }

        const { key, ctrlKey, altKey, shiftKey, metaKey } = event;
        let modifierKeys = [];
        if (ctrlKey) modifierKeys.push('Ctrl');
        if (shiftKey) modifierKeys.push('Shift');
        if (altKey) modifierKeys.push('Alt');
        const combo = `${modifierKeys.join('+')}${modifierKeys.length ? '+' : ''}${key}`.toLocaleLowerCase();
        if (this.hotkeysConfig[combo]) {
            event.stopPropagation();
            event.preventDefault();
        }

        if (this.hotkeys[combo]) {
            this.hotkeys[combo].forEach(callback => {
                callback(event);
            });
        }
    }
}


export default Hotkey